package middlewares

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"tools-api/src/common/db/redis"
	"tools-api/src/routes/response"
)

// RateLimit 限速器
func RateLimit() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		key := fmt.Sprintf("rate:request:%s", ctx.ClientIP())
		ok := redis.RateAllow(ctx, key, 20) // 每秒限制请求20次最多
		if !ok {
			response.FailByCode(ctx, response.RateForbidden, "您的请求速度太快了")
			return
		}
		ctx.Next()
	}

}
